#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File  :repair_bill_pdf_page.py
# Time  :2025/4/18 13:57
# Email :fortunatedong@163.com
# Author:by Adonli

import os
from io import BytesIO
import zipfile
import pandas as pd
import streamlit as st

from config import ROOT_DIR
from utils.hr_task.repair_pdf import RepairBillPDF
from config import Header_space
Header_space()
current_repair_table_dir = os.path.join(ROOT_DIR, 'Datas/hr_repair_pdf/current_repair_table')
repair_pdf_result_dir = os.path.join(ROOT_DIR, 'Datas/hr_repair_pdf/repair_pdf_result')
repair_table_path = ""
copy_repair_table_path = ""
st.subheader("批量生成保修单内容", divider=True)
head_col1,head_col2,head_col3,head_col4,head_col5 = st.columns([1,1,1,1,1])

# if "upload_plan_choose" not in st.session_state:
#     st.session_state.upload_plan_choose = False
with head_col1:
    upload_plan_choose = st.selectbox(
        ":blossom:**选择方案（必选）**",
        ("选择方案","保单文件上传", "保单内容粘贴"),
        # placeholder="选择方案"
    )
# with head_col4:
    # head_col4_col1, head_col4_col2 = st.columns([1, 1])
    # with head_col4_col2:
    #     st.button("生成pdf")
with head_col5:
    head_col5_col1, head_col5_col2 = st.columns([1, 1])
    with head_col5_col1:
        create_pdf_button = st.button("保单内容生成PDF",type="primary")
    # with head_col5_col2:
    #     download_pdf_button = st.button("下载pdf")
col1, col2 = st.columns([5,3])
if upload_plan_choose == "保单文件上传":
    with col1:
        current_repair_table_file = st.file_uploader(
            ":blossom:**方案一：上传理光保单文件:**", accept_multiple_files=False,
        )
        if current_repair_table_file is not None:
            bytes_data = current_repair_table_file.getvalue()
            # cfg['HRTASK']['HRLastDepartmentFileName'] = current_repair_table_file.name
            # with open(configs_toml, 'w', encoding="utf-8") as f:
            #     toml.dump(cfg, f)
            with open(f"{current_repair_table_dir}/{current_repair_table_file.name}", "wb") as f:
                f.write(bytes_data)
            st.write(":blossom:**当前保单文件表格内容如下：**")
            repair_table_path = f"{current_repair_table_dir}/{current_repair_table_file.name}"
            repair_table_df = pd.read_excel(repair_table_path)
            st.dataframe(repair_table_df)
elif upload_plan_choose == "保单内容粘贴":
    copy_repair_table_path = f"{current_repair_table_dir}/copy_repair_table.xlsx"
    if not os.path.exists(copy_repair_table_path):
        df = pd.DataFrame(
            [
                {"交货/安装日期": "", "上报时间": "", "机型（规格型号）": "", "机身号（序列号）": "",
                 "客户名称": "", "联系人": "", "电话": "", "联系地址": "",
                 "章": "", "图": "", "经手人": "",},
            ]
        )
        df.to_excel(f"{current_repair_table_dir}/copy_repair_table.xlsx", index=False)


    df = pd.read_excel(f"{current_repair_table_dir}/copy_repair_table.xlsx",dtype=str)
    with col1:
        config = {
            '交货/安装日期': st.column_config.TextColumn(),
            '上报时间': st.column_config.TextColumn(),
            '机型（规格型号）': st.column_config.TextColumn(),
            '机身号（序列号）': st.column_config.TextColumn(),
            '客户名称': st.column_config.TextColumn(),
            '联系人': st.column_config.TextColumn(),
            '电话': st.column_config.TextColumn(),
            '联系地址': st.column_config.TextColumn(),
            '章': st.column_config.TextColumn(),
            '图': st.column_config.TextColumn(),
            '经手人': st.column_config.TextColumn(),
        }
        result = st.data_editor(df, column_config=config, num_rows='dynamic')
        if st.button('保存'):
            result.to_excel(copy_repair_table_path, index=False)
            st.write(result)

if create_pdf_button:
    with col2:
        if upload_plan_choose == "保单文件上传":
            with st.spinner("Wait for it...", show_time=True):
                input_repair_pdf = RepairBillPDF(repair_table_path)
                pdf_names = input_repair_pdf.generate_repair_pdf()
                st.dataframe(pdf_names)
                pdf_names_list = list(map(lambda x: f"{repair_pdf_result_dir}/{x}", pdf_names))
                # print(pdf_names_list)
                def create_zip_files():
                    zip_buffer = BytesIO()
                    with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED, False) as zip_file:
                        for pdf_name_file in pdf_names_list:
                            file_path = os.path.join(repair_pdf_result_dir, pdf_name_file)
                            pure_filename = os.path.basename(pdf_name_file)
                            zip_file.write(file_path, arcname=pure_filename)
                    zip_buffer.seek(0)
                    return zip_buffer.getvalue()


                with head_col5_col2:
                    zip_data = create_zip_files()
                    st.download_button(
                        label="批量下载保单PDF",
                        data=zip_data,
                        file_name="保修单PDF文件.zip",
                        mime="application/zip"
                    )
        elif upload_plan_choose == "保单内容粘贴":
            with st.spinner("Wait for it...", show_time=True):
                input_repair_pdf = RepairBillPDF(copy_repair_table_path)
                pdf_names = input_repair_pdf.generate_repair_pdf()
                st.dataframe(pdf_names)
                pdf_names_list = list(map(lambda x:f"{repair_pdf_result_dir}/{x}", pdf_names))
                # print(pdf_names_list)
                def create_zip_files():
                    zip_buffer = BytesIO()
                    with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED, False) as zip_file:
                        for pdf_name_file in pdf_names_list:
                            file_path = os.path.join(repair_pdf_result_dir, pdf_name_file)
                            pure_filename = os.path.basename(pdf_name_file)
                            zip_file.write(file_path, arcname=pure_filename)
                    zip_buffer.seek(0)
                    return zip_buffer.getvalue()
                with head_col5_col2:
                    zip_data = create_zip_files()
                    st.download_button(
                        label="批量下载保单PDF",
                        data=zip_data,
                        file_name="保修单PDF文件.zip",
                        mime="application/zip"
                    )

        else:st.warning("先选择方案，上传保单内容！")